from flask import Flask
from flask import request
import json, os, datetime, random
app = Flask(__name__)

@app.route('/upload', methods=['GET', 'POST'])
def index():
    # open file
    seed = random.randint(1000, 10000)
    print(1,seed)
    filename = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S ') + str(seed)+'.txt'
    print(filename)
    print(type(request.values))
    print(request.values['data'])
    try:
        global file
        data_ = request.values['data']
        if data_ is None:
            return
        try:
            json_ = json.loads(data_)
            path = os.getcwd()+'\data'
            print('path',path)
            file = open("./data/"+ filename, "a+")
            if os.path.isdir(path) is True:
                print("hello")
                for index in range(len(json_['data'])):
                    file.write(str(json_['data'][index]) + '\n')
                    print(index, json_['data'][index])
                return "ok"
            else:
                 os.mkdir("data")
        except Exception as e:
            file.write(request.values['data'])
            print('Wrong file type',)
        finally:
            file.close()
    except Exception as e:
        print(e)
        return 'Exception'
    # read the content of the file
    # r = requests.post("http://172.16.201.144:8080/ecg/ecgs/testresolve")
    # print(type(r.text))
    return 'hello'

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5000, debug=True)
